

//
//  YYYComposeView.swift
//  HotNews
//
//  Created by YYY on 2017/11/1.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit
import pop

class YYYComposeView: UIView {
    private let buttonInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "YYYComposeController"],
                              ["imageName": "tabbar_compose_photo", "title": "照片／视频"],
                              ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                              ["imageName": "tabbar_compose_lbs", "title": "签到"],
                              ["imageName": "tabbar_compose_review", "title": "点评"],
                              ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"],
                              ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                              ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                              ["imageName": "tabbar_compose_music", "title": "音乐"],
                              ["imageName": "tabbar_compose_shooting", "title": "拍摄"]
    ]
    //logo图片
    private lazy var logoImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    //滑动视图
    private lazy var middleScrollView = UIScrollView(frame: CGRect(x: 0, y: kDeviceHeight - 290, width: kDeviceWidth, height: 224), isBounces: false)
    //关闭按钮
    private lazy var closeButton = UIButton(imageStr: "tabbar_compose_background_icon_close", backgroundImageStr: nil, target: self, action: #selector(closeAction))
    
    //返回按钮
    private lazy var returnButton = UIButton(imageStr: "tabbar_compose_background_icon_return", backgroundImageStr: nil, target: self, action: #selector(returnAction))
    
    //底部视图
    private lazy var bottomView = UIView(frame: CGRect(x: 0, y: kDeviceHeight-44, width: kDeviceWidth, height: 44))
    override init(frame: CGRect) {
        super.init(frame: frame)
        //初始化控件
        setupUI()
    
        //设置视图动画
        addViewAnimation()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func clickme(selectBtn: YYYComposeButton)
    {
        //滑动偏移量
        let page = Int(middleScrollView.contentOffset.x/middleScrollView.width)
        let tempView = middleScrollView.subviews[page]
        for (i, btn) in tempView.subviews.enumerated()
        {
            //缩放动画
            let scaleAnimation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            scaleAnimation.duration = 0.5
            let scale = (selectBtn == btn) ? 1.5 : 0.5
            scaleAnimation.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            btn.pop_add(scaleAnimation, forKey: nil)
            
            //透明度动画
            let alphaAnimation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnimation.toValue = 0.4
            alphaAnimation.duration = 0.5
            btn.pop_add(alphaAnimation, forKey: nil)
            
            if i == 0
            {
                alphaAnimation.completionBlock = { _,_ in
                    //动画执行完成的回调
                    self.animationCompletionBlock(selectBtn: selectBtn)
                }
            }
        }
    }
    
    //动画执行完成的回调
    func animationCompletionBlock(selectBtn: YYYComposeButton)
    {
        guard let clsName = selectBtn.clsName,
            let classString = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type else
        {
            self.removeFromSuperview()
            return
        }
        let nextVC = classString.init()
        
        let navVC = UINavigationController(rootViewController: nextVC)
        UIApplication.shared.keyWindow?.rootViewController?.present(navVC, animated: true, completion: {
            self.removeFromSuperview()
        })
    }

    //更多事件
    @objc private func clickMore()
    {
        print("点击更多")
        //滑动视图滑到第二页
        middleScrollView.setContentOffset(CGPoint(x: middleScrollView.width, y: 0), animated: true)
        
        //取消隐藏
        returnButton.isHidden = false
        
        UIView.animate(withDuration: 0.33) {
            self.closeButton.center.x += kDeviceWidth/6
            self.returnButton.center.x -= kDeviceWidth/6
        }
    }
    //关闭事件
    @objc private func closeAction()
    {
        //设置隐藏按钮动画
        addHideButtonsAnimation()
    }
    //返回事件
    @objc private func returnAction()
    {
        //滑动视图滑倒第一页
        middleScrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        
        UIView.animate(withDuration: 0.33, animations: {
            self.closeButton.center.x = kDeviceWidth/2.0
            self.returnButton.center.x = kDeviceWidth/2.0
            self.returnButton.alpha = 0
        }) { (_) in
            //隐藏
            self.returnButton.isHidden = true
            self.returnButton.alpha = 1
        }
    }
}

extension YYYComposeView
{
    //初始化控件
    func setupUI()
    {
        backgroundColor = UIColor.clear
        //设置毛玻璃效果
        blurEffectShow()
        
        addSubview(logoImageView)
        addSubview(middleScrollView)
        addSubview(bottomView)
        bottomView.addSubview(closeButton)
        bottomView.addSubview(returnButton)
        
        logoImageView.center.x = self.center.x
        logoImageView.setTop(newTop: 120)

        //滑动视图中的按钮展示布局
        //超出边界不裁剪
        middleScrollView.clipsToBounds = false
        
        setupViews()
        
        bottomView.backgroundColor = UIColor.white
        closeButton.center.x = bottomView.center.x
        closeButton.setTop(newTop: (bottomView.height - closeButton.height)/2.0)
        returnButton.frame = closeButton.frame
        returnButton.isHidden = true
    }
}

private extension YYYComposeView
{
    // MARK: 设置毛玻璃效果
    func blurEffectShow()
    {
        //创建一个模糊效果
        let blurEffect = UIBlurEffect(style: .light)
        //创建一个承载模糊效果的视图
        let blurView = UIVisualEffectView(effect: blurEffect)
        //设置模糊视图的大小
        blurView.frame = kMainScreenBounds
        addSubview(blurView)
    }
    
    //按钮展示布局
    func setupViews()
    {
        let rect = middleScrollView.bounds
        for i in 0..<2
        {
            let tempView = UIView(frame: rect.offsetBy(dx: CGFloat(i) * kDeviceWidth, dy: 0))
            middleScrollView.addSubview(tempView)
            addButtons(newView: tempView, index: i * 6)
        }
        middleScrollView.contentSize = CGSize(width: CGFloat(2) * kDeviceWidth, height: 0)
        //禁止滑动
        middleScrollView.isScrollEnabled = false
    }
    //添加多个按钮
    func addButtons(newView: UIView, index: Int)
    {
        for i in index ..< (6 + index)
        {
            if i >= buttonInfo.count
            {
                break
            }
            let dict = buttonInfo[i]
            guard let imageStr = dict["imageName"],
                  let titleStr = dict["title"] else
            {
                continue
            }
          
            let composeBtn = YYYComposeButton(imageStr: imageStr, titleStr: titleStr)
            if let actionName = dict["actionName"]
            {
                composeBtn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            else
            {
                composeBtn.addTarget(self, action: #selector(clickme), for: .touchUpInside)
            }
            composeBtn.clsName = dict["clsName"]
            let margin = (newView.width - 3 * composeBtn.width) / 4.0
            let col = i % 3
            let x = margin + CGFloat(col) * (composeBtn.width + margin)
            var y: CGFloat
            
            if index == 0
            {
                y = (i > 2) ? (newView.height - composeBtn.height) : 0
            }
            else
            {
                y = (i > 8) ? (newView.height - composeBtn.height) : 0
            }
            composeBtn.frame.origin = CGPoint(x: x, y: y)
            newView.addSubview(composeBtn)
        }
    }
    //设置视图动画
    func addViewAnimation()
    {
        //创建动画
        let animation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        //设置动画属性
        animation.fromValue = 0
        animation.toValue = 1
        animation.duration = 0.5
        //添加动画
        pop_add(animation, forKey: nil)
        
        //设置按钮动画
        addShowButtonsAnimation()
    }
    
    //设置显示按钮动画
    func addShowButtonsAnimation()
    {
        let tempView = middleScrollView.subviews[0]
        
        for (i, btn) in tempView.subviews.enumerated()
        {
            //创建动画
            let animation: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            //设置动画属性
            animation.fromValue = btn.center.y + 300
            animation.toValue = btn.center.y
            animation.springBounciness = 8
            animation.springSpeed = 8
            
            animation.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            //添加动画
            btn.pop_add(animation, forKey: nil)
        }
    }
    //设置隐藏按钮动画
    func addHideButtonsAnimation()
    {
        //滑动视图偏移量
        let offset = Int(middleScrollView.contentOffset.x/middleScrollView.width)
        //滑动视图的当前子视图
        let tempView = middleScrollView.subviews[offset]
        
        for (i, btn) in tempView.subviews.enumerated().reversed()
        {
            //创建动画
            let animation: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            //设置动画属性
            animation.fromValue = btn.center.y
            animation.toValue = btn.center.y + 300
            //弹力系数，默认4 [0,12]
            animation.springBounciness = 8
            //弹力速度，默认12 [0,20]
            animation.springSpeed = 8
            
            animation.beginTime = CACurrentMediaTime() + CFTimeInterval(tempView.subviews.count - i) * 0.025
            //添加动画
            btn.pop_add(animation, forKey: nil)
            
            if i == 0
            {
                //最后一个按钮
                //执行完动画,添加视图的透明度动画
                animation.completionBlock = { (_,_)->() in
                    //视图透明度动画
                    self.alphaAnimation()
                }
            }
        }
    }
    
    //视图透明度动画
    private func alphaAnimation()
    {
     
        let animation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        animation.fromValue = 1
        animation.toValue = 0
        animation.duration = 0.5
        pop_add(animation, forKey: nil)
        animation.completionBlock = { _,_ in
            self.removeFromSuperview()
        }
    }
}
